<html>
<head>
  <title>Movie Vote</title>
  <link rel="stylesheet" type="text/css" href="/static/style.css" />
</head>
<script>
var XMLHttpRequestObject = new Array();

function GetXMLHttpRequest() 
{
  var object = null;
  if (window.XMLHttpRequest) {
    object = new XMLHttpRequest();
  } 
  else if (window.ActiveXObject) {
    try {
      object = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
    }
    if (object == null) {
      try {
        object = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e) {
      }
    }
  }
  if (object == null) {
    alert("Your browser does not support AJAX");
  }
  return object;
}

function ProcessXMLVote(movie_name, vote_type) {
  url = encodeURI(vote_type + '/json/' + movie_name + '/');
  movie_name = escape(movie_name);
  var requestObject = GetXMLHttpRequest();
  if (requestObject) {
    XMLHttpRequestObject[movie_name] = new Object();
    XMLHttpRequestObject[movie_name].requestObject = requestObject;
    requestObject.onreadystatechange = new Function ("OnVoteProcess('" + movie_name + "')");
    requestObject.open("GET", url, true);
    requestObject.send("");
  }
}

function ProcessXMLReload() {
  // Don't do a reload if anything else is inflight
  for (i in XMLHttpRequestObject) {
    if (XMLHttpRequestObject[i]) {
      return;
    }
  }
  url = 'json/' + window.location.search;
  var requestObject = GetXMLHttpRequest();
  if (requestObject) {
    XMLHttpRequestObject['RELOAD'] = new Object();
    XMLHttpRequestObject['RELOAD'].requestObject = requestObject;
    requestObject.onreadystatechange = new Function ("OnReloadProcess('RELOAD')");
    requestObject.open("GET", url, true);
    requestObject.send("");
  }
}

function OnReloadProcess(reload_name) {
  obj = XMLHttpRequestObject[reload_name].requestObject;
  // 4 means the response has been returned and ready to be processed
  if (obj.readyState == 4) {
    // 200 means "OK"
    if (obj.status == 200) {
      skip_reload = 0;
      for (i in XMLHttpRequestObject) {
        if (i == reload_name) {
          continue;
        }
        if (XMLHttpRequestObject[i]) {
          // Something else is in flight
          skip_reload = 1;
          break;
        }
      }
      if (!skip_reload) {
        // process whatever has been sent back here:
        jsonData = eval('(' + obj.responseText + ')');
        ReloadTable(jsonData);
      }
    } else {
      alert("There was a problem in the returned data:\n");
    }
    XMLHttpRequestObject[reload_name] = null;
  }
}

function OnVoteProcess(movie_name) {
  obj = XMLHttpRequestObject[movie_name].requestObject;
  // 4 means the response has been returned and ready to be processed
  if (obj.readyState == 4) {
    // 200 means "OK"
    if (obj.status == 200) {
      // process whatever has been sent back here:
      jsonData = eval('(' + obj.responseText + ')');
      UpdateMovie(jsonData);
    } else {
      alert("There was a problem in the returned data:\n");
    }
    XMLHttpRequestObject[movie_name] = null;
    ProcessXMLReload();
  }
}

function ReloadTable(json) {
  rows = document.getElementsByTagName("table")[0].getElementsByTagName("tr");
  for (i = 1; i < rows.length; i++) {
    if (XMLHttpRequestObject[json[i-1].name]) {
      // An update is in flight
      continue;
    }
    UpdateRow(rows[i], json[i-1], 1);
  }
}

function UpdateRow(row, movie_info, all_fields) {
  need_fade = 0;
  if (all_fields && row.id != movie_info.name) {
    need_fade = 1;
    // Update all cells of the row
    // First is name
    row.id = movie_info.name;
    row.cells[0].innerHTML = '';
    if (movie_info.imdb_url) {
      link = document.createElement("a");
      link.href = movie_info.imdb_url;
      link.innerHTML = movie_info.name;
      row.cells[0].appendChild(link);
    } else {
      row.cells[0].innerHTML = movie_info.name;
    }

    // Second is reviews
    row.cells[1].innerHTML = '';
    if (movie_info.rotten_url) {
      link = document.createElement("a");
      link.href = movie_info.rotten_url;
      link.innerHTML = '<img src="/static/images/rotten.ico" alt="Rotten Tomatoes" title="Rotten Tomatoes">';
      row.cells[1].appendChild(link);
      row.cells[1].appendChild(document.createTextNode(' '));
    }
    if (movie_info.metacritic_url) {
      link = document.createElement("a");
      link.href = movie_info.metacritic_url;
      link.innerHTML = '<img src="/static/images/metacritic.ico" alt="Metacritic" title="Metacritic">';
      row.cells[1].appendChild(link);
    }
    if (!isNaN(movie_info.review_average_score)) {
      score = document.createTextNode(' ' + movie_info.review_average_score);
      row.cells[1].appendChild(score);
    }

    // Tally happens below, but we need to update vote images
    images = row.cells[3].getElementsByTagName("img");
    if (movie_info.voted == "1") {
      images[0].src = images[0].src.replace(/plus_(off|on)/, 'plus_on');
      images[1].src = images[1].src.replace(/minus_(off|on)/, 'minus_off');
    } else if (movie_info.downvoted == "1") {
      images[0].src = images[0].src.replace(/plus_(off|on)/, 'plus_off');
      images[1].src = images[1].src.replace(/minus_(off|on)/, 'minus_on');
    } else {
      images[0].src = images[0].src.replace(/plus_(off|on)/, 'plus_off');
      images[1].src = images[1].src.replace(/minus_(off|on)/, 'minus_off');
    }
  }

  tally_cell = row.cells[2];
  if (movie_info.downvoter_count != "0" || movie_info.voter_count != "0" ||
      movie_info.screenings != "0") {
    tally = tally_cell.getElementsByTagName("a")[0];
    if (!tally) {
      // Special case, previous 0 counts need to be urlified
      tally_cell.removeChild(tally_cell.firstChild);
      tally = document.createElement("a");
      tally_cell.appendChild(tally);
      tally_cell.appendChild(document.createTextNode(' '));
      tally_detail = document.createElement("span");
      tally_detail.className = "smaller";
      tally_cell.appendChild(tally_detail);
    }
    tally.href = "voters/" + movie_info.name + '/';
    tally.innerHTML = movie_info.tally;
    tally_detail = tally_cell.getElementsByTagName("span")[0];
    tally_detail.innerHTML = movie_info.tally_detail;
  } else {
    tally_cell.innerHTML = movie_info.tally;
  }
  // Change row to gray if screened
  if (movie_info.screenings != "0") {
    row.className = "viewed";
  } else {
    row.className = "";
  }
    
  if (need_fade) {
    // Effects.fade(row.id, 0, 100, 1000);
  }
}

function UpdateMovie(json) {
  movie_name = json.name;
  row = document.getElementById(movie_name);
  progress_cell = row.cells[row.cells.length-1];
  UpdateRow(row, json, 0);
  row.removeChild(progress_cell);
}

function OnVote(image) {
  movie_name = image.parentNode.parentNode.id;
  if (XMLHttpRequestObject[movie_name] != null) {
    // a click of this movie is in flight
    return;
  }
  row = image.parentNode.parentNode;
  progress_cell = row.cells[row.cells.length-1];
  if (!progress_cell.getElementsByTagName("img").length) {
    // a click is also inflight if there is an 'Updating...' cell added
    return;
  }

  // If there is a click on an off image, it must turn off the other image
  plus_img = image.parentNode.getElementsByTagName("img")[0];
  minus_img = image.parentNode.getElementsByTagName("img")[1];
  if (image == plus_img) {
    vote_type = 'plusvote'
    other_img = minus_img;
  } else {
    vote_type = 'minusvote'
    other_img = plus_img;
  }
  
  if (image.src.match('off')) {
    if (other_img.src.match('on')) {
      other_img.src = other_img.src.replace(/on/, 'off');
    } else {
      image.src = image.src.replace(/off/, 'on');
    }
  } else if (image.src.match('on')) {
    if (vote_type == 'plusvote') {
      vote_type = 'minusvote';
    } else {
      vote_type = 'plusvote';
    }
    image.src = image.src.replace(/on/, 'off');
  }
  // Add a progress indicator 'Updating...'
  newcell = document.createElement("td");
  newcell_text = document.createTextNode("Updating...");
  newcell.appendChild(newcell_text);
  row.appendChild(newcell);

  ProcessXMLVote(movie_name, vote_type);
}
  
Effects = {};
Effects.fade = function(id, opacStart, opacEnd, duration)
{
  Effects.changeOpacity(0, id);
  var speed = Math.round(duration/100);
  var timer = 0;

  if(opacStart > opacEnd)
  {
   for(var i=opacStart; i>=opacEnd; i--)
   {
    setTimeout("Effects.changeOpacity("+ i +", "+ id +", "+ opacEnd +")", (timer*speed));
    timer++;
   }
  }
  else if(opacStart < opacEnd)
  {
   for(var i=opacStart; i<=opacEnd; i++)
   {
    setTimeout("Effects.changeOpacity("+ i +", "+ id +", "+ opacEnd +")", (timer*speed));
    timer++;
   }
  }
}

Effects.changeOpacity = function(opacity, id, endPoint)
{
  var _style = document.getElementById(id).style;
  // alert(_style);
 _style.opacity = (opacity / 100);
 _style.MozOpacity = (opacity / 100);
 _style.KhtmlOpacity = (opacity / 100);
 _style.filter = "alpha(opacity=" + opacity + ")";
}
</script>
<body>

<h1>Movie Vote</h1>

<div class="log_box">
You are logged in as <a href="{% url vote.views.user_stats %}">{{ user.username }}</a>.<br />
<a href="{% url django.contrib.auth.views.logout_then_login %}">Logout</a>
<a href="{% url vote.views.password_change %}">Change Password</a>
</div>

<p>
Add or remove votes for any movies you'd like to see.  The movies with the
highest number of voters will go to the top. A <a
href="/static/weighting.html">weighting function</a> is applied to your vote.
Once we have watched a movie, its votes will be reset to 0. Movies in gray have
already been shown and will get a -N vote where N is the number of screenings.
</p>

<form action="">
<p>
  Search: <input type="text" name="namelike" value="{{ search_value }}">
  Sorting by {{ sort_description }}.
  {% for link in sort_links %}
    <a href="{% url vote.views.index %}?{{ link.url }}{% if search_value %}&namelike={{ search_value }}{% endif %}">
    {{ link.desc }}</a>.
  {% endfor %}
</p>
</form>

<p>
{% if count %}
  {% ifnotequal prev start %}
    <a href="{% url vote.views.index %}?count={{ count }}&start={{ first }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/first.png" alt="First Page" title="First Page" /></a>
    <a href="{% url vote.views.index %}?count={{ count }}&start={{ prev }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/prev.png" alt="Previous Page" title="Previous Page" /></a>
  {% else %}
    <img src="/static/images/first-grey.png" alt="First Page" title="First Page" />
    <img src="/static/images/prev-grey.png" alt="Previous Page" title="Previous Page" />
  {% endifnotequal %}
  
  <a href="{% url vote.views.index %}?count=0&start={{ start }}&old_count={{ count }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/show-all.png" alt="Show All" title="Show All" /></a>

  {% ifnotequal next start %}
    <a href="{% url vote.views.index %}?count={{ count }}&start={{ next }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/next.png" alt="Next Page" title="Next Page" /></a>
    <a href="{% url vote.views.index %}?count={{ count }}&start={{ last }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/last.png" alt="Last Page" title="Last Page" /></a>
  {% else %}
    <img src="/static/images/next-grey.png" alt="Next Page" title="Next Page" />
    <img src="/static/images/last-grey.png" alt="Last Page" title="Last Page" />
  {% endifnotequal %}
{% else %}
  <a href="{% url vote.views.index %}?count={{ old_count }}&start={{ first }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/first.png" alt="First Page" title="First Page" /></a>
  <img src="/static/images/prev-grey.png" alt="Previous Page" title="Previous Page" /><a href="{% url vote.views.index %}?count={{ old_count }}&start={{ start }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/show-some.png" alt="Show {{ old_count }} at a time" title="Show {{ old_count }} at a time" />
  </a>
  <img src="/static/images/next-grey.png" alt="Next Page" title="Next Page" />
  <a href="{% url vote.views.index %}?count={{ old_count }}&start={{ last }}{% if search_value %}&namelike={{ search_value}}{% endif %}"><img src="/static/images/last.png" alt="Last Page" title="Last Page" /></a>
{% endif %}
</p>

<table cellspacing=0px class="movie_list">
  <tr>
    <th>Name</th>
    <th>Reviews</th>
    <th>Tally</th>
    <th>Vote</th>
  </tr>
  {% for movie in movies %}
  {% if movie.screenings %}
  <tr id="{{ movie.name }}" class="viewed">
  {% else %}
  <tr id="{{ movie.name }}">
  {% endif %}
    <td>
    {% if movie.imdb_url %}
      <a href="{{ movie.imdb_url }}">{{ movie.name }}</a>
    {% else %}
      {{ movie.name }}
    {% endif%}
    </td>
    <td align="right">
    {% if movie.rotten_url %}
      <a href="{{ movie.rotten_url }}"><img src="/static/images/rotten.ico" alt="Rotten Tomatoes" title="Rotten Tomatoes"></a>
    {% endif%}
    {% if movie.metacritic_url %}
      <a href="{{ movie.metacritic_url }}"><img src="/static/images/metacritic.ico" alt="Metacritic" title="Metacritic"></a>
    {% endif%}
    {% if movie.review_average_score %}
      {{ movie.review_average_score }}
    {% endif %}
    </td>
    <td align="right">
    {% if movie.downvoter_count or movie.voter_count or movie.screenings %}
      <a href="{% url vote.views.voters movie_name=movie.name %}">
      {{ movie.tally }}</a>
      <span class="smaller">{{ movie.tally_detail }}</span>
    {% else %}
      {{ movie.tally }}
    {% endif %}
    </td>
    <td align="center">
    {% if movie.voted %}
      <img src="/static/images/plus_on.png" onmouseover="this.style.cursor='pointer'" onclick="OnVote(this)" alt="Minus Vote"></a>
      <img src="/static/images/minus_off.png" onmouseover="this.style.cursor='pointer'" onclick="OnVote(this)" alt="Minus Vote"></a>
    {% else %}
      {% if movie.downvoted %}
        <img src="/static/images/plus_off.png" onmouseover="this.style.cursor='pointer'" onclick="OnVote(this)" alt="Plus Vote"></a>
        <img src="/static/images/minus_on.png" onmouseover="this.style.cursor='pointer'" onclick="OnVote(this)" alt="Plus Vote"></a>
      {% else %}
        <img id="plus" src="/static/images/plus_off.png" onmouseover="this.style.cursor='pointer'" onclick="OnVote(this)" alt="Plus Vote"></a>
        <img id="minus" src="/static/images/minus_off.png" onmouseover="this.style.cursor='pointer'" onclick="OnVote(this)" alt="Minus Vote"></a>
      {% endif %}
    {% endif %}
    </td>
  </tr>  
  {% endfor %}
</table>

</body>
</html>
